/*
 * @Author: ylyu
 * @Date: 2024-02-22 13:55:06
 * @LastEditors: ylyu
 * @LastEditTime: 2024-02-24 10:29:27
 * @Description:
 */
import instance from './axios'
import axios from 'axios'

const CancelToken = axios.CancelToken

let sources = []

export function AppPost(url, data) {
  return new Promise((resolve, reject) => {
    instance
      .post(url, data, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
        // 取消请求
        cancelToken: new CancelToken(function executor(c) {
          // An executor function receives a cancel function as a parameter
          sources.push(c)
        }),
      })
      .then((res) => {
        // console.log(res)
        if (res.status === 200) {
          if (res.data.code === 0) {
            resolve(res.data)
          } else {
            reject(res.data.msg || '服务错误')
          }
        } else {
          reject(new Error(`${res.msg}`) || res.status)
        }
      })
      .catch((err) => {
        reject(err || 'Error')
      })
  })
}
export function AppPost2(url, data) {
  return new Promise((resolve, reject) => {
    instance
      .post(url, data, {
        // headers: {
        //   'Content-Type': 'multipart/form-data',
        // },
        // 取消请求
        cancelToken: new CancelToken(function executor(c) {
          // An executor function receives a cancel function as a parameter
          sources.push(c)
        }),
      })
      .then((res) => {
        // console.log(res)
        if (res.status === 200) {
          if (res.data.code === 0) {
            resolve(res.data)
          } else {
            reject(res.data.msg || '服务错误')
          }
        } else {
          reject(new Error(`${res.msg}`) || res.status)
        }
      })
      .catch((err) => {
        reject(err || 'Error')
      })
  })
}
export function AppGet(url, data) {
  return new Promise((resolve, reject) => {
    instance
      .get(
        url,
        { params: data },
        {
          headers: {
            'Content-Type': 'application/json',
          },
          // 取消请求
          cancelToken: new CancelToken(function executor(c) {
            // An executor function receives a cancel function as a parameter
            sources.push(c)
          }),
        }
      )
      .then((res) => {
        // console.log(res)
        if (res.status === 200) {
          if (res.data.code === 0) {
            resolve(res.data)
          } else {
            reject(res.data.msg || '服务错误')
          }
        } else {
          reject(new Error(`${res.msg}`) || res.status)
        }
      })
      .catch((err) => {
        reject(err || 'Error')
      })
  })
}

export { sources }
